import React, { useCallback, useEffect, useState } from 'react';
import { PlaneForm, PlaneTable } from './Components';

import { getAllPlane } from '@apis/index';

import { Plane } from '../../types/plane.type';
export const PlaneManager = () => {
    const [open, setOpen] = useState(false);
    const [planes, setPlanes] = useState<Plane[] | undefined>();
    const [loading, setLoading] = useState(true);
    const [selectedPlane, setSelectedPlane] = useState<Plane | undefined>();
    const handleGetAllPlane = useCallback(() => {
        setLoading(true);
        getAllPlane().then((data) => {
            setPlanes(data);
        }).finally(
            () => setLoading(false)
        )
    }, [])

    useEffect(() => {
        if (planes === undefined) {
            handleGetAllPlane();
        }
    }, [handleGetAllPlane, planes]);
    const onOk = useCallback(() => {
        handleGetAllPlane();
    }, [handleGetAllPlane]);
    return <>
        <PlaneForm
            setSelectedPlane={setSelectedPlane}
            selectedPlane={selectedPlane}
            onOk={onOk}
            open={open}
            setOpen={setOpen} />
        <PlaneTable
            handleGetAllPlane={handleGetAllPlane}
            selectedPlane={selectedPlane}
            setSelectedPlane={setSelectedPlane}
            data={planes} loading={loading}
            setOpen={setOpen}
        />
    </>
}